package vip.zhenzicheng.algorithm.leetcode.linked_list;

import vip.zhenzicheng.algorithm.ListNode;
import vip.zhenzicheng.algorithm.leetcode.str.AddStrings_415;

/**
 * <a href="https://leetcode.cn/problems/add-two-numbers/">两数相加 [中等]</a>
 * 参考:{@link AddStrings_415}
 *
 * @author zhenzicheng
 * @date 2022-06-21 13:31
 */
public class AddTwoNumbers_2 {

  public static void main(String[] args) {
    AddTwoNumbers_2 test = new AddTwoNumbers_2();
    ListNode node1 = new ListNode(7).next = new ListNode(2).next = new ListNode(8);
    ListNode node2 = new ListNode(4).next = new ListNode(3).next = new ListNode(2).next = new ListNode(9);

    test.addTwoNumbers(node1, node2);
  }

  public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    int carry = 0; // 进位
    ListNode head = new ListNode(-1), cur = head; // 定义初始节点

    while (l1 != null || l2 != null || carry != 0) {
      // res = 0;
      if (l1 != null) {
        carry += l1.val;
        l1 = l1.next;
      }
      if (l2 != null) {
        carry += l2.val;
        l2 = l2.next;
      }

      cur.next = new ListNode((carry) % 10);
      cur = cur.next;
      carry /= 10; // 清空进位
    }

    return head.next; // 返回链表头
  }
}
